import { globalStore } from '@/store';
const gStore = globalStore();
class WeChatShareService {
  static instance;
  vm;
  constructor(vm) {
    this.vm = vm;
    this.init();
  }

  static getInstance(vm) {
    if (WeChatShareService.instance === undefined) {
      console.warn(
        'No WeChatShareService instance found. New WeChatShareService instance will be created.',
      );
      WeChatShareService.instance = new WeChatShareService(vm);
    }
    return WeChatShareService.instance;
  }

  async init() {
    let sdkConfig = await this.fetchSDKConfig();
    let shareConfig = {};
    try {
      shareConfig = await this.getShareInfo(); // 在 config.js 中进行分享相关的配置
      jWeixin.showOptionMenu();
    } catch (err) {
      if (err?.code == 401) {
        gStore.isBindMobile = true;
        jWeixin.hideOptionMenu();
      }
    }
    await this.initWXSDK(sdkConfig, shareConfig);
  }
  // 获取分享信息
  getJsapiInfo(options, shareConfig) {
    return new Promise((resolve, reject) => {
      uni.$request
        .service({
          url: '/wx/jsapi/config',
          method: 'POST',
          data: options,
          isToast: true,
          isLoading: true,
        })
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }
  async fetchSDKConfig() {
    // 调用后端接口，获取 appId, timestamp, nonceStr, signature
    return await this.getJsapiInfo({
      url: location.href,
    }).then((res) => {
      const { appid, nonceStr, signature, timestamp } = res;
      return {
        appId: appid || uni.$appId,
        timestamp: timestamp,
        nonceStr: nonceStr,
        signature: signature,
      };
    });
  }
  initWXSDK({ appId, timestamp, nonceStr, signature }, shareConfig) {
    return new Promise((resolve, reject) => {
      jWeixin.config({
        debug: false,
        appId: appId,
        timestamp: timestamp,
        nonceStr: nonceStr,
        signature: signature,
        jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData'],
      });

      jWeixin.ready(() => {
        this.updateShareData(shareConfig);
        resolve();
      });

      jWeixin.error((error) => {
        reject(error);
      });
    });
  }
  getShareInfo() {
    return new Promise((resolve, reject) => {
      uni.$request
        .service({
          url: '/m/wx/share',
          method: 'POST',
          data: {},
          isToast: true,
          isLoading: true,
        })
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }
  updateShareData({ title, desc, link, imgUrl }) {
    if (title && desc && link && imgUrl) {
      jWeixin.updateAppMessageShareData({
        title: title,
        desc: desc,
        link: link,
        imgUrl: imgUrl,
        success: function () {
          // 设置成功
          console.log('updateAppMessageShareData success');
        },
      });

      jWeixin.updateTimelineShareData({
        title: title,
        link: link,
        imgUrl: imgUrl,
        success: function () {
          // 设置成功
          console.log('updateTimelineShareData success');
        },
      });
    } else {
      console.log('updateTimelineShareData finally');
    }
  }
}

export default WeChatShareService;
